#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanSanmenxiaPolicy(BaseTaxPolicySpider):
    name = 'henan_sanmenxia_re_policy'
    
    province = '河南省'
    city = '三门峡市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['三门峡市渑池县人民政府', "渑池县", "https://www.mianchi.gov.cn/pageView/zhengfuxinxi.html?lmid=23341&rlmid=23322"],
            ['三门峡市渑池县人民政府', "渑池县", "https://www.mianchi.gov.cn/pageView/zhengfuxinxi.html?lmid=23342&rlmid=23322"],
            ['三门峡市陕州区人民政府', "陕州区", "https://www.shanzhou.gov.cn/pageView/zhengfuxinxi.html?lmid=18005&rlmid=18002"],
            ['三门峡市陕州区人民政府', "陕州区", "https://www.shanzhou.gov.cn/pageView/zhengfuxinxi.html?lmid=18032&rlmid=18002"],
            ['三门峡市人民政府', "", "https://www.smx.gov.cn/pageView/zhengfuxinxi.html?lmid=4498&rlmid=4021"],
            ['三门峡市人民政府', "", "https://www.smx.gov.cn/pageView/zhengfuxinxi.html?lmid=4495&rlmid=4021"],
            ['三门峡市人民政府', "", "https://www.smx.gov.cn/pageView/zhengfuxinxi.html?lmid=26026&rlmid=4021"],
            ['三门峡市人民政府', "", "https://www.smx.gov.cn/pageView/zhengfuxinxi.html?lmid=4501&rlmid=4021"],
        ]:
            params = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
            item = {'source': source, 'county': county}
            url = url.split("?")[0]
            yield scrapy.Request(url + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': item, "params": params, "url": url}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath("""//script""").re(r'"href"\:\s*"(.*?html)"'):
            item = Item()
            item['source_url'] = elem.replace(r'\/', '/')
            item['source_url'] = response.urljoin(item['source_url'])
            # item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if '.htm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total = response.xpath(""".""").re_first(r"const\s*total\s*=\s*'(\d+)'") or response.xpath(""".""").re_first(r"共(\d+)篇")
            pageSize = response.xpath(""".""").re_first(r"const\s*pageSize\s*=\s*'(\d+)'") or response.xpath(""".""").re_first(r"(\d+)篇/页")
            totalpage = math.ceil(int(total) / int(pageSize))
            params = response.meta.get('params')
            print(response.url, 'page:', totalpage)
            for page in range(1, int(totalpage) + 1):
                url = response.url.split("?")[0]
                params['pageNum'] = page
                yield response.follow(url + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布日期：') or contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_sanmenxia_re_policy".split())
